using Microsoft.Extensions.DependencyInjection;

namespace Naruto.CQRS.Query;

public sealed class QueryDispatcher : IQueryDispatcher
{
    private readonly IServiceProvider _serviceProvider;

    /// <summary>
    /// 
    /// </summary>
    /// <param name="serviceProvider"></param>
    public QueryDispatcher(IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="event"></param>
    /// <param name="cancellationToken"></param>
    /// <typeparam name="TEvent"></typeparam>
    /// <typeparam name="TResult"></typeparam>
    /// <returns></returns>
    public async Task<TResult> SendAsync<TEvent, TResult>(TEvent @event, CancellationToken cancellationToken = default) where TEvent : IQueryEvent
    {
        var service = _serviceProvider.GetRequiredService<IQuery<TEvent, TResult>>();
        return await service.HandleAsync(@event,cancellationToken);
    }
}